package com.vip.websocket.controller;

import com.vip.websocket.service.PublishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * WebSocket Controller
 *
 * @author wgb
 * @date 2020/4/12 19:42
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/socket")
public class WebSocketController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 指定发送Socket消息
     *
     * @param topic
     * @param id
     * @param msg
     * @return
     */
    @PostMapping("/send/{topic}/{id}")
    public ResponseEntity sendMsg(@PathVariable("topic") String topic, @PathVariable("id") String id, @RequestParam String msg) {
        try {
            topic = String.format("%s:%s", topic, id);
            PublishService ps = new PublishService();
            ps.publish(topic, msg);
        } catch (Exception e) {
            log.error(String.format("给 topic :%s id: %s 发送消息出错了", topic, id), e);
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 群发Socket消息
     *
     * @param topic
     * @param msg
     * @return
     */
    @PostMapping("/send/{topic}")
    public ResponseEntity sendAllMsg(@PathVariable("topic") String topic, String msg) {
        try {
            Set<String> keys = redisTemplate.keys(String.format("%s*", topic));
            assert keys != null;
            keys.forEach(t -> {
                PublishService ps = new PublishService();
                ps.publish(t, msg);
            });
        } catch (Exception e) {
            log.error("发送消息出错了", e);
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
}
